<?php
namespace im;

use MongoDB\Client;
use MongoDB\BSON\UTCDateTime;
use im\cache\ExRedis;

require_once __DIR__.'/../../vendor/autoload.php';
 
class Message{
    
    const CHAT_UID_KEY_PRE = "chat_uid_";
    const CHAT_FD_MAP_KEY = 'chat_user_map'; // uid->fd
    const CHAT_VAL_TO_KEY_MAP = 'chat_fd_map';// fd->uid
    //== 消息历史记录
    const CHAT_USER_HISTORY_KEY = "chat_history_msg_";  
    const CHAT_HISTORY_USER_KEY = 'chat_msg_uid_'; //消息历史子键
    //== 未读消息统计
    const CHAT_UNREAD_MSG_COUNT = "chat_unread_record_"; // 和用户联系人相映射 子键值： uid_[user_id]
    const CHAT_UNREAD_MSG_SUM = "chat_unread_sum"; //HASH TABLE，存储用户总共有多少未读消息,和具体未读消息有关联作用
    const CHAT_USER_LINKS = "chat_msg_links_"; //用户联系人,拼接 chat_msg_links_uid
    const CHAT_UNREAD_USER_KEY = "uid_";
    //== 记录已经读取消息的时间
    const CHAT_READ_MAP_KEY = "chat_read_map_";

    static public $mongo = null;
    static public $options = [
        'host'       => '115.159.215.139',
        'port'       => 7788,
        'password'   => 'test.zxmall.mongo',
        'user'     => 'test',
        'database' =>'test'
    ];

    //获取MONGODB连接
    public static function getStore(){

        if (!extension_loaded('mongodb')) {
            throw new Exception('_NOT_SUPPERT_:Mongodb');
        }

        if(is_null(self::$mongo)){
            $link =  'mongodb://'.self::$options['user'].":".rawurlencode(self::$options['password']).'@'.self::$options['host'].':'.self::$options['port'].'/'.self::$options['database'].'?connectTimeoutMS=3000';
            self::$mongo = new Client($link);
        }

        return self::$mongo;
    }

    //向集合中保存数据
    public static function store($table,$data_obj){
        $collection = self::getStore()->selectCollection(self::$options['database'],$table);
        return $collection->insertOne($data_obj);
    }

    //获取MONGODB集合
    public static function getCollect($table){
       return self::getStore()->selectCollection(self::$options['database'],$table);
    }

    //根据发送者和接收者ID 返回当前时间之前的未读消息记录
    public static function getUnreadMessage($from_uid,$to_uid){

        $today_time = (time()+(8*60*60))*1000;
        $today = new UTCDateTime($today_time);
        $result = ["count"=>0,"data"=> [] ];

        $count = self::getCollect('message')->count(
            [
                'from_uid'=>$from_uid,
                'to_uid'=>$to_uid,
                'read_time'=>0,
                'create_time'=>[ '$lt'=>$today ]
            ],
            [ 'sort' => ['create_time'=>-1] ]
        );
        $result['count'] = $count;

        if($count > 0){
            $data = self::getCollect('message')->find(
                [
                    'from_uid'=>$from_uid,
                    'to_uid'=>$to_uid,
                    'read_time'=>0,
                    'create_time'=>[ '$lt'=>$today ]
                ],
                [ 'sort' => ['create_time'=>-1] ]
            );

            $result['data'] = $data;
        }

        return $result;
    }

    //消息时间转换
    public static function changeDisplayTime($current_time){

        $today_start_time = mktime(0,0,0);
        $today_end_time = mktime(23,59,59);

        if($current_time >= $today_start_time && $today_start_time <= $today_end_time ){
            $time_str = date('今天 H:i:s',$current_time);
        }else{
            $time_str = date('Y年m月d日 H:i:s',$current_time);
        }

        return $current_time;
    }

    //对MESSAGE设置阅读时间
    public static function setReadTime($from_uid,$to_uid){
        $read_time_timestample = (time()+(8*60*60))*1000;
        $read_time = new UTCDateTime($read_time_timestample);
        return self::getCollect('message')->updateMany(
            [
                'from_uid'=>$from_uid,
                'to_uid'=>$to_uid,
                'read_time'=>0
            ],
            [ '$set' => ['read_time'=>$read_time] ]
        );
    }

    //对应减少未读消息计数,非cli
    public static function decrUnreadCount($from_uid,$to_uid){
        //将未读信息数量清空，对应发送者减少
        $unread_key = Message::CHAT_UNREAD_MSG_COUNT.$from_uid;
        $f_user_key = Message::CHAT_UNREAD_USER_KEY.$to_uid;
        //清空所有此人发的未读消息计数
        $user_unread_count_num = 0;
        if(ExRedis::getInstance()->hExists($unread_key,$f_user_key)){
            $user_unread_count_num = ExRedis::getInstance()->hGet($unread_key,$f_user_key);
        }
        ExRedis::getInstance()->hSet($unread_key,$f_user_key,0);

        //设置总数减少
        $unread_count_num = 0;
        $unread_sum_key = Message::CHAT_UNREAD_USER_KEY.$from_uid; //接收者总数KEY
        if(ExRedis::getInstance()->hExists(Message::CHAT_UNREAD_MSG_SUM,$unread_sum_key)){
            $unread_count_num = ExRedis::getInstance()->hGet(Message::CHAT_UNREAD_MSG_SUM,$unread_sum_key);
            $unread_count_num = ( $unread_count_num >= $user_unread_count_num) ? ($unread_count_num - $user_unread_count_num) : ($unread_count_num);
        }

        ExRedis::getInstance()->hSet(Message::CHAT_UNREAD_MSG_SUM,$unread_sum_key,$unread_count_num);
    }
}